<%-- 
    Document   : page
    Created on : 2014/8/21, 上午 09:27:45
    Author     : Benny
--%>

<%@page import="java.util.HashMap"%>
<%@page import="java.util.ArrayList"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
    String username =request.getParameter("username");
    String where =" ";
    if(username != null && !"".equals(username)){
        where =" where username like '%" + username + "%'";
    }
    dao.BasDAO y =new dao.BasDAO();
    String sql ="select count(*) as total from person" +where;
    String ary[] ={};
    ArrayList list =y.query(sql, ary);
    String total =(String)((HashMap)list.get(0)).get("total");
    //System.out.println(list);
    int pagesize =10; //每頁的筆數
    int pages =Integer.parseInt(total) / pagesize; //總頁數
    if (Integer.parseInt(total) % pagesize !=0)
        pages++;
    String pageNo =request.getParameter("pageNo"); //使用者指定的頁碼
    if(pageNo == null)
        pageNo ="1";
    int index =(Integer.parseInt(pageNo) -1) * pagesize; //資料庫中開始的位置
    sql ="select * from person " + where + " limit "+ index +", "+ pagesize;
    //ary =new String[]{index+"",+ index+"" };
    list =y.query(sql, ary);
    System.out.println(list);
    int lastPage =Integer.parseInt(pageNo) ==1?1:Integer.parseInt(pageNo)-1; //上一頁設定
    int nextPage =Integer.parseInt(pageNo) ==pages?pages:Integer.parseInt(pageNo)+1; //下一頁設定
    request.setAttribute("list", list);
%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Page</title>
    </head>
    <body>
        <h1>-----Page-----</h1>
        <hr>
        <form action="page.jsp" id="form1">
            查詢條件：<input type="text" name ="username" value="${param.username}">
            <input type="hidden" name="pageNo" id="pageNo" value="1">
            <input type="submit" value="查詢">
            </form>
            <input type="button" value="上一頁" onclick="goPage('<%= lastPage %>')">
        <!--<a href="page.jsp?pageNo=<%= lastPage %>">上一頁</a>-->
        總共有<%= total %>筆資料, 目前頁碼<%= pageNo %>, 每頁<%= pagesize %>, 共有<%= pages %>頁
            <input type="button" value="下一頁" onclick="goPage('<%= nextPage %>')">
        <!--<a href="page.jsp?pageNo=<%= nextPage %>">下一頁</a>-->
        <hr>
        <c:forEach var="x" items="${list}">
            ${x.id},${x.username},${x.tel},${x.birthday}<br>
        </c:forEach>
        <script>
            function goPage(x){    
                    document.getElementById('pageNo').value =x;
                    document.getElementById('form1').submit();
            }
       </script>
    </body>
</html>
